<template>
  <div class="panel">

    <el-form v-if="type==='create'||type==='edit'" ref="contentFormRef" :model="dataFrom" :rules="dataRules" label-width="100px">

      <el-form-item label="类目" prop="category" required>
        <el-select v-model="dataFrom.category" filterable placeholder="选择类目">
          <el-option v-for="(item,index) in typeList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="发布渠道" prop="releaseChannel">
        <div style="color:#aaa">选择需要发布的渠道，发布后将内容展示到相应版块</div>
        <el-checkbox-group v-model="dataFrom.releaseChannel">
          <el-checkbox v-for="(item,index) in channelList" :key="index" :label="item.id">{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item> -->

      <el-form-item label="标题" prop="title">
        <el-input v-model="dataFrom.title" style="width: 100%;" maxlength="64" show-word-limit placeholder="输入标题" />
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <tinymce v-model:value="dataFrom.content" style="width:100%" />
      </el-form-item>

      <el-form-item label="封面" required prop="image">
        
        <upload-oss list-type="picture-card" :limit="1" :imageUrl="operate.imageUrl" :beforeUpload="(file)=>beforeUpload(file)" @upload="afterUpload"></upload-oss>
      </el-form-item>

      <el-form-item label="内容来源" prop="contentSource" required>
        <el-radio-group v-model="dataFrom.contentSource">
          <el-radio :label="1">原创</el-radio>
          <el-radio :label="2">转载</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="编辑" prop="editor">
        <el-input v-model="dataFrom.editor" style="width: 400px;" maxlength="20" show-word-limit placeholder="输入编辑" />
      </el-form-item>

      <el-form-item label="定时发布" prop="releaseTime" :rules="dataFrom.isTime?{ required:true, message: '请选择发布时间', trigger:'blur'}:{}">
        <el-switch v-model="dataFrom.isTime" @change="switchReleaseTime"></el-switch>
        <el-date-picker style="margin-left:16px" v-if="dataFrom.isTime" v-model="dataFrom.releaseTime" type="datetime" placeholder="选择发布时间" value-format="YYYY-MM-DD HH:mm:ss" :picker-options="expireTimeOption">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="saveLoading" @click="saveHandle">保存</el-button>
      </el-form-item>

    </el-form>

    <el-form v-else :model="dataFrom" label-width="100px">

      <el-form-item label="类目" prop="category">
        <div>{{getArrayItem("typeList","id",dataFrom.category).name}}</div>
      </el-form-item>

      <!-- <el-form-item label="发布渠道" prop="category">
        <div>{{turnChannels(dataFrom.releaseChannel)}}</div>
      </el-form-item> -->

      <el-form-item label="标题" prop="title">
        <div>{{dataFrom.title}}</div>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <div v-html="dataFrom.content" class="richContent" style="background: #f5f5f5;border-radius: 4px;overflow-y: auto;padding: 8px;min-height: 120px;max-height:620px;"></div>
      </el-form-item>

      <el-form-item label="封面" required>
        <div>
          <img style="max-width: 480px;" v-if="dataFrom.image" :src="`https://img.qumoyugo.com${dataFrom.image}`">
          <span v-else>暂无封面</span>
        </div>
      </el-form-item>

      <el-form-item label="内容来源" prop="contentSource" required>
        <div>{{dataFrom.contentSource===1?'原创':'转载'}}</div>
      </el-form-item>

      <el-form-item label="编辑" prop="editor">
        <div>{{dataFrom.editor}}</div>
      </el-form-item>

      <el-form-item label="定时发布">
        <div v-if="dataFrom.isTime">{{dataFrom.releaseTime}}</div>
        <div v-else>无</div>
      </el-form-item>

    </el-form>
  </div>
</template>

<script>
import Tinymce from "@/components/Tinymce";
import { ElNotification } from "element-plus";
// import Pagination from "@/components/Pagination";
import UploadOss from "@/components/AliOSS";
import imageViewer from "@/components/imageViewer/index2";
import {
  createBlogstoreOne,
  getBlogstoreOne,
  editBlogstoreOne,
} from "@/api/blogstore";
import { client, randomWord } from "@/utils/alioss";
import { ElMessage } from "element-plus";

const baseUrl = "https://img.qumoyugo.com";
export default {
  name: "blogstoreCreate",
  components: {
    Tinymce,
    UploadOss,
    // Pagination,
  },
  props: {
    type: {
      type: String,
      default: "",
    },
    refresh: Boolean,
  },
  data() {
    return {
      TYPE: "", //DETAIL/EDIT/ADD
      editId: "",

      dataFrom: {
        category: "",
        // releaseChannel: [],
        title: "",
        content: "",
        image: "",
        contentSource: "",
        editor: "",
        isTime: 0,
        releaseTime: "",
      },
      operate:{
        imageUrl: undefined,
      },
      dataRules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        content: [
          {
            required: true,
            message: "请输入内容",
            trigger: ["blur", "change"],
          },
        ],
        image: [
          {
            required: true,
            message: "请上传封面图片",
            trigger: ["blur", "change"],
          },
        ],
        contentSource: [
          { required: true, message: "请选择来源", trigger: "change" },
        ],
        editor: [{ required: true, message: "请输入编辑", trigger: "blur" }],
      },
      tempRoute: {},
      saveLoading: false,
      expireTimeOption: {
        disabledDate(date) {
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      channelList: [
        // {name: "全部", id: ""},
        { name: "趣摸鱼平台资讯", id: 1 },
        { name: "供销端产业动态", id: 2 },
      ],
      typeList: [
        // {name: "全部",id:""},
        { name: "新闻", id: 1 },
        { name: "资讯", id: 2 },
        { name: "广告", id: 3 },
        { name: "系统", id: 4 },
        { name: "其他", id: 5 },
      ],
    };
  },
  watch:{
    refresh(nv,ov){
      this.getDetail();
    }
  },
  created() {
    if (this.type === "edit" || this.type === "detail") {
      this.getDetail();
    }

    this.checkoutResult = false; //图片相关

    this.tempRoute = Object.assign({}, this.$route);
  },
  methods: {
    getDetail() {
      getBlogstoreOne(this.$route.params.id).then(({ code, data }) => {
        if (code === 0) {
          // 返回刷新
          console.log("data:", data);
          this.dataFrom = {
            category: data.category,
            // releaseChannel: (() => {
            //   return [[], [1], [2], [1, 2]][data.releaseChannel || 0];
            // })(),
            contentSource: data.contentSource,
            title: data.title,
            releaseTime: data.releaseTime,
            status: data.status,
            content: data.content,
            image: data.image,
            editor: data.editor,
            isTime: !!data.isTime,
            id: data.id,
          };
          this.operate.imageUrl = data.image?[{url:baseUrl + data.image}]:undefined;
        }
      });
    },
    // 检查图片大小和尺寸
    beforeUpload(file){
      return new Promise((resolve, reject) => {
        const size = file.size / 1024;
        if (size > 300) {
          ElMessage.error("图片大小不能超过 300 KB!");
          reject();
          return;
        }
        let URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload =  () => {
          if (img.width !== img.height){
            ElMessage.error("请上传1:1尺寸的图片");
            reject();
            return;
          }
          resolve();
        };
        img.src = URL.createObjectURL(file);
      });
    },
    afterUpload(list){
      const url = list[0];
      if (!url) {
        this.dataFrom.image = "";
        this.operate.imageUrl = undefined;
        return;
      }
      this.dataFrom.image = url.showUrl;
      this.operate.imageUrl = [{url:baseUrl + url.showUrl}]
    },

    switchReleaseTime(val) {
      if (!val) {
        this.dataFrom.releaseTime = undefined;
      }
    },

    saveHandle() {
      // 保存
      this.$refs["contentFormRef"].validate((valid) => {
        if (!valid) {
          return;
        }
        let handleSaveFun =
          this.type === "edit" ? editBlogstoreOne : createBlogstoreOne; // 判断是修改还是新增
        this.saveLoading = true;

        let req = (() => {
          let query = {
            ...this.dataFrom,
            // releaseChannel: (() => {
            //   let len = this.dataFrom.releaseChannel.length;
            //   return len === 0
            //     ? 0
            //     : len === 2
            //     ? 3
            //     : this.dataFrom.releaseChannel[0];
            // })(),
            isTime: this.dataFrom.isTime ? 1 : 0,
          };
          if (this.type === "edit") {
            query.id = this.$route.params.id;
          }
          return query;
        })();
        console.log("req:", { ...req });
        // return;
        handleSaveFun(req)
          .then(({ code }) => {
            this.saveLoading = false;
            if (code === 0) {
              ElNotification({
                title: "成功",
                message:
                  this.type === "edit" ? "修改内容成功！" : "发布内容成功！",
                type: "success",
                duration: 2000,
              });
              // 返回刷新
              this.$store
                .dispatch("tagsView/delView", this.tempRoute)
                .then(() => {
                  this.$router.replace({ path: "/blogstore/list" });
                });
            }
          })
          .catch(() => {
            this.saveLoading = false;
          });
      });
    },
    
    // 获取数组某一项
    getArrayItem(listName, key, value) {
      let list = this[listName] || [];
      for (let prop of list) {
        if (prop[key] === value) {
          return prop;
        }
      }
      return {};
    },
  },
};
</script>

<style scoped lang="scss">
.panel {
  background-color: #ffffff;
  padding: 12px;
  border-radius: 8px;
}
.isEmpty {
  color: rgb(172, 172, 172);
}
</style>